package manage.service;

import m.common.model.util.*;
import m.common.service.Service;
import m.system.RuntimeData;
import m.system.db.DBManager;
import m.system.db.DataRow;
import m.system.exception.MException;
import m.system.util.*;
import manage.model.ImageAdmin;
import manage.model.ImageInfo;
import manage.model.ImageLink;
import manage.model.SystemInfo;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ImageInfoService extends Service {

	public void updateAllLinkNum() throws MException, SQLException {
		List<ImageInfo> list=ModelQueryList.getModelList(ImageInfo.class, new String[] {"*"}, null, null);
		for(ImageInfo img : list) {
			img.setLinkNum(ImageLinkService.getLinkNum(img.getOid()));
			ModelUpdateUtil.updateModel(img, "linkNum");
		}
	}
	public static void updateLinkNum(String imageOid) throws MException, SQLException {
		ImageInfo model=new ImageInfo();
		model.setOid(imageOid);
		model.setLinkNum(ImageLinkService.getLinkNum(imageOid));
		ModelUpdateUtil.updateModel(model, "linkNum");
	}

	public void convertThum(String imageOid,Double thumWidth) throws Exception {
		ImageInfo model=ModelQueryList.getModel(ImageInfo.class, imageOid, new String[] {"*"},false);
		model.setThumWidth(thumWidth);
		File file=FileUtil.getPublicFile(model.getImgPath());
		ImageUtil.saveThumFile(file, model.getThumPath(), model.getThumWidth().intValue(),new Double(model.getThumWidth()/model.getThumRatio()).intValue());
		ModelUpdateUtil.updateModel(model, "thumWidth");
	}

	/**
	 * 保持图片  可调用方法，参数都不能为空
	 */
	public static ImageInfo saveImage(File file,String userOid,String imageType,Double thumRatio,Double thumWidth) throws Exception {
		ImageInfo image=new ImageInfo();
		image.setImageAdmin(new ImageAdmin());
		image.getImageAdmin().setOid(userOid);
		image.setImageType(imageType);
		image.setThumRatio(thumRatio);
		image.setThumWidth(thumWidth);
		RuntimeData.getService(ImageInfoService.class).saveImage(image,file);
		return image;
	}
	/**
	 * 保存图片 系统使用，请勿调用
	 */
	public void saveImage(ImageInfo model, File file) throws Exception {
		String key=GenerateID.generatePrimaryKey();
		StringBuilder fPath=new StringBuilder(RuntimeData.getFilePath()).append("image/")
			.append(DateUtil.format(new Date(),"yyyyMM")).append("/");
		String fName= key + ".jpg";
		//
		SystemInfo si=getService(SystemInfoService.class).getUniqueModel();
		int maxWidth=960,thumWidth=150;
		if("B".equals(si.getImageMode())){
			maxWidth=1440;thumWidth=225;
		}else if("C".equals(si.getImageMode())){
			maxWidth=1920;thumWidth=300;
		}
		if(null==model.getThumWidth()) model.setThumWidth((double) thumWidth);
		String[] farr=file.getName().split("_uploadFile_");
		model.setName(farr.length>1?farr[1]:farr[0]);
		model.setPath(fPath + fName);
		model.setImgPath(fPath + "image" + fName);
		model.setThumPath(fPath + "thum" + fName);
		ImageUtil.saveFile(file, model.getPath(),1920);
		File f=FileUtil.getFile(RuntimeData.getPublicWeb() + model.getPath());
		ImageUtil.saveFile(f, model.getImgPath(),maxWidth);
		ImageUtil.saveThumFile(f, model.getThumPath(), model.getThumWidth().intValue(),new Double(model.getThumWidth()/model.getThumRatio()).intValue());
		model.setOid(key);
		model.setCreateDate(new Date());
		ModelUpdateUtil.insertModel(model);
		updateLinkNum(model.getOid());
		//将上传的文件同步到主控服务器上
//		sendFile2Server("", new String[]{model.getImgPath(),model.getThumPath()});
	}
//	/**
//	 * 将上传的文件同步到主控服务器上
//	 *  adminToken
//	 *  paths
//	 *  Exception
//	 */
//	private void sendFile2Server(String adminToken,String[] paths) throws Exception{
//		try{//将上传的文件同步到主控服务器上
//			HostInfo host=RuntimeData.getHostInfo();
//			if(!(null==host||host.getMain()==1)){//不是主控服务器
//				StringBuffer url=new StringBuffer("http://").append(RuntimeData.getServerIp()).append(":80/action/manage/imageInfo/synchFile?adminToken=").append(adminToken);
//				List<String> ps=new ArrayList<String>();
//				List<String> ns=new ArrayList<String>();
//				List<File> files=new ArrayList<File>();
//				for(String path : paths){
//					File f=FileUtil.getWebFile(path);
//					files.add(f);
//					ps.add(URLEncoder.encode(path,"UTF-8"));
//					ns.add(URLEncoder.encode(f.getName(),"UTF-8"));
//				}
//				url.append("&synchPath[]=").append(ArrayUtil.connection(ps.toArray(new String[]{}), ","));
//				url.append("&synchName[]=").append(ArrayUtil.connection(ns.toArray(new String[]{}), ","));
//				new HttpRequestUtil().doUpload(url.toString(), files.toArray(new File[]{}));
//				//SystemUtil.println("同步完成!");
//			}else{
//				//SystemUtil.println("主控服务器,不用同步!");
//			}
//		}catch(Exception e){
//			//SystemUtil.println("文件同步失败:"+e.getMessage());
//		}
//	}
//	/**
//	 * 保存图片
//	 *  path
//	 *  file
//	 */
//	public void saveSynchFile(String path,File file){
//		try {
//			if(!FileUtil.existsWebFile(path)){
//				FileUtil.writeWebFile(path,new FileInputStream(file));
//			}
//		} catch (FileNotFoundException e) {
//			//SystemUtil.println("文件同步失败:"+e.getMessage());
//		}
//	}

	/**
	 * 保存并关联图片
	 *  model
	 *  file
	 *  businessOid
	 *  Exception
	 */
	public void saveImageAndSelect(ImageInfo model, File file, String businessOid) throws Exception {
		saveImage(model,file);
		ImageLinkService.addImageLink(businessOid, "图片列表", model.getOid());
	}
	/**
	 * 返回未使用或者已使用的图片列表 
	 *  admin
	 *  page
	 *  imageType
	 *  isUsed
	 * 
	 *  SQLException
	 *  MException
	 */
	public List<ImageInfo> getImageList(ImageAdmin admin,QueryPage page,String imageType,String name,boolean isUsed) throws Exception{
		QueryCondition condition=QueryCondition.in("oid", ModelQueryList.instance(ImageLink.class, new String[]{"imageInfo.oid"}, null,
			QueryCondition.or(
				QueryCondition.eq("imageAdmin.oid", admin.getOid()),
				QueryCondition.isEmpty("imageAdmin.oid"))
		));
		if(!isUsed){
			condition=QueryCondition.not(condition);
		}
		List<QueryCondition> conList=new ArrayList<>();
		conList.add(QueryCondition.or(
			QueryCondition.eq("imageAdmin.oid", admin.getOid()),
			QueryCondition.isEmpty("imageAdmin.oid")
		));
		conList.add(condition);
		conList.add(QueryCondition.eq("imageType", imageType));
		if(!StringUtil.isSpace(name)){
			conList.add(QueryCondition.like("name",name));
		}
		ModelQueryList util = ModelQueryList.instance(ImageInfo.class, new String[]{"oid","name","thumPath","imgPath"}, page,
			QueryCondition.and(conList.toArray(new QueryCondition[0])),
			QueryOrder.desc("createDate"));
		return ModelQueryList.getModelList(util.setUseStaticField(false));
	}
	/**
	 * 返回业务对应的图片列表
	 *  businessOid
	 *  page
	 *  imageType
	 * 
	 *  SQLException
	 *  MException
	 */
	public List<ImageInfo> getImageList(String businessOid,QueryPage page,QueryOrder order,String imageType) throws Exception{
		if(null==order) order=QueryOrder.desc("createDate");
		QueryCondition condition=QueryCondition.in("oid", ModelQueryList.instance(ImageLink.class, new String[]{"imageInfo.oid"}, null,QueryCondition.eq("businessOid", businessOid)));
		return ModelQueryList.getModelList(ImageInfo.class, new String[]{"oid","name","thumPath","imgPath","imageAdmin.oid"}, page,
			QueryCondition.and(QueryCondition.and(condition,QueryCondition.eq("imageType", imageType))),
			order);
	}
	/**
	 * 根据oid数组获取图片
	 *  oids
	 *  page
	 *  order
	 * 
	 *  SQLException
	 *  MException
	 */
	public List<ImageInfo> getImageList(String[] oids,QueryPage page,QueryOrder order) throws Exception{
		return getImageList(oids, page, order, true);
	}
	/**
	 * 根据oid数组获取图片
	 *  oids
	 *  page
	 *  order
	 *  isStatic 是否使用静态
	 * 
	 *  SQLException
	 *  MException
	 */
	public List<ImageInfo> getImageList(String[] oids,QueryPage page,QueryOrder order,boolean isStatic) throws Exception{
		List<QueryCondition> condList= new ArrayList<>();
		for(String oid : oids){
			condList.add(QueryCondition.eq("oid", oid));
		}
		ModelQueryList util=ModelQueryList.instance(ImageInfo.class, new String[]{"oid","name","thumPath","imgPath"}, page,
			QueryCondition.or(condList.toArray(new QueryCondition[]{})), 
			order);
		util.setUseStaticField(isStatic);
		return ModelQueryList.getModelList(util);
	}
	/**
	 * 根据图片oid, 获取图片html标签
	 *  oids
	 * 
	 *  Exception
	 */
	public static String getImageDetails(String[] oids) throws Exception {
		List<ImageInfo> list=getService(ImageInfoService.class).getImageList(oids, new QueryPage(0,oids.length), QueryOrder.asc("createDate"),false);
		StringBuilder sb=new StringBuilder();
		for(ImageInfo image : list) {
			sb.append("<img src=\"").append(image.getImgPath()).append("\">");
		}
		return sb.toString();
	}
	/**
	 * 拷贝图片到另一个用户下
	 *  oid
	 *  adminOid
	 *  imageType
	 * 
	 *  Exception
	 */
	public static String copyImage(String oid,String adminOid,String imageType) throws Exception {
		ImageInfo image=new ImageInfo();
		image.setOid(oid);
		image=ModelQueryList.getModel(image, new String[] {"*"},false);
		image.setOid("");
		ImageAdmin admin=new ImageAdmin();
		admin.setOid(adminOid);
		image.setImageAdmin(admin);
		image.setImageType(imageType);
		getService(ImageInfoService.class).saveImage(image, FileUtil.getPublicFile(image.getImgPath()));
		return image.getOid();
	}
	/**
	 * 拷贝图片到另一个用户下
	 *  oids
	 *  admin
	 *  imageType
	 * 
	 *  Exception
	 */
	public static String[] copyImageList(String[] oids,String adminOid,String imageType) throws Exception {
		List<String> newList= new ArrayList<>();
		for(String oid : oids) {
			newList.add(copyImage(oid,adminOid,imageType));
		}
		return newList.toArray(new String[] {});
	}
	/**
	 * 删除未使用的图片
	 *  admin
	 *  imageOid
	 * 
	 *  Exception
	 */
	public String delete(ImageAdmin admin, String imageOid) throws Exception {
		return delete(admin,imageOid,null,null);
	}
	private String delete(ImageAdmin admin, String imageOid, String businessOid,String business) throws Exception {
		ImageInfo ii=new ImageInfo();
		ii.setOid(imageOid);
		ii=ModelQueryUtil.getModel(ii);
		if(ii.getImageAdmin().getOid().equals(admin.getOid())||"1".equals(admin.getOid())){
			if(!StringUtil.isSpace(businessOid)&&StringUtil.noSpace(business).equals("图片列表")) {
				ImageLinkService.removeBusinessLink(businessOid, imageOid);
			}
			if(ImageLinkService.hasImageLink(imageOid)){
				throw new MException(this.getClass(),"已被使用的图片不能删除");
			}
			DataRow dr=DBManager.queryFirstRow("select img_path,thum_path,path from os_image_info where oid=?",imageOid);
			if(!StringUtil.isSpace(dr.get(String.class, "img_path"))) FileUtil.deletePublicFile(dr.get(String.class, "img_path"));
			if(!StringUtil.isSpace(dr.get(String.class, "thum_path"))) FileUtil.deletePublicFile(dr.get(String.class, "thum_path"));
			if(!StringUtil.isSpace(dr.get(String.class, "path"))) FileUtil.deletePublicFile(dr.get(String.class, "path"));
			ModelUpdateUtil.deleteModel(ii);
			return imageOid;
		}else{
			throw new MException(this.getClass(),"不能删除不属于自己的图片");
		}
	}
	/**
	 * 取消业务关联并删除图片
	 *  admin
	 *  imageOid
	 *  businessOid
	 * 
	 *  Exception
	 */
	public String deleteBusiness(ImageAdmin admin, String imageOid,String businessOid) throws Exception{
		return delete(admin,imageOid,businessOid,"图片列表");
	}
}
